import { useEffect, useState } from "react";
import Layout from "../Shared/Layout";
import MyButton from "../../Components/MyButton";
import { Tree, Input, Descriptions, Popconfirm, message } from "antd";
import { request, requestDispatch } from "../../Api/api";
import { useDispatch } from "react-redux";
import { CarryOutOutlined, PlusOutlined } from "@ant-design/icons";
import AddJob from "../../Components/Operation/Job/AddJob";
const Job = () => {
  const [jobTrees, setJobTrees] = useState([]);
  const [currentJob, setCurrentJob] = useState({});
  const [addingJob, setAddingJob] = useState({
    name: "",
    explain: "",
    departmentId: undefined,
  });
  const [updatingJob, setUpdatingJob] = useState({});
  const [isUpdating, setIsUpdating] = useState(false);
  const [addShow, setAddShow] = useState(false);
  const [expandedKeys, setExpandedKeys] = useState([]);
  const dispatch = useDispatch();
  useEffect(() => {
    async function fetchData() {
      let res = await requestDispatch(dispatch, "/job/tree", {}, "get");
      setCurrentJob(getFistJob(res.data));
      let data = concatDepJobTree(res.data);
      setJobTrees(data);
      setExpandedKeys(getAllKeys(data));
    }
    // 获取所有节点的 key
    const getAllKeys = (data) => {
      let keys = [];
      data.forEach((item) => {
        keys.push(item.id);
        if (item.childrenDeps) {
          keys = keys.concat(getAllKeys(item.childrenDeps));
        }
      });
      return keys;
    };
    const getFistJob = (data) => {
      for (let i = 0; i < data.length; i++) {
        const d = data[i];
        if (d.childrenJobs.length > 0) {
          return d.childrenJobs[0];
        } else {
          return getFistJob(d.childrenDeps);
        }
      }
      return { id: "", name: "", explain: "" };
    };
    const concatDepJobTree = (data) => {
      return data.reduce((acc, cur) => {
        const concatChildren = concatDepJobTree(cur.childrenDeps);
        acc.push({
          ...cur,
          name: (
            <div style={{ cursor: "default" }}>
              {cur.name}
              &nbsp; &nbsp;
              <span style={{ cursor: "pointer" }}>
                <PlusOutlined
                  onClick={(e) => {
                    e.stopPropagation();
                    showAddModal(cur.id);
                  }}
                />
              </span>
            </div>
          ),
          childrenDeps: [
            ...concatChildren.map((dep) => ({
              ...dep,
            })),
            ...cur.childrenJobs.map((job) => ({
              ...job,
              icon: <CarryOutOutlined />,
            })),
          ],
        });
        return acc;
      }, []);
    };
    fetchData();
  }, [dispatch]);
  const getFistJob = (data) => {
    for (let i = 0; i < data.length; i++) {
      const d = data[i];
      if (d.childrenJobs && d.childrenJobs.length > 0) {
        return d.childrenJobs[0];
      } else {
        return getFistJob(d.childrenDeps);
      }
    }
    return { id: "", name: "", explain: "" };
  };
  const items = [
    {
      key: "1",
      label: "编号",
      children: <p>{currentJob.id}</p>,
    },
    {
      key: "2",
      label: "名称",
      children: isUpdating ? (
        <div>
          <Input
            value={updatingJob.name}
            onChange={(e) =>
              setUpdatingJob({ ...updatingJob, name: e.target.value })
            }
          ></Input>
        </div>
      ) : (
        <p>{currentJob.name}</p>
      ),
    },
    {
      key: "3",
      label: "创建时间",
      children: <p>{new Date(currentJob.createTime).toLocaleDateString()}</p>,
    },
    {
      key: "4",
      label: "描述",
      children: isUpdating ? (
        <div>
          <Input.TextArea
            rows={4}
            value={updatingJob.explain}
            onChange={(e) =>
              setUpdatingJob({ ...updatingJob, explain: e.target.value })
            }
          ></Input.TextArea>
        </div>
      ) : (
        <p>{currentJob.explain}</p>
      ),
    },
  ];
  // 选择职位
  const selectedChange = (keys, e) => {
    if (e.selected) {
      setCurrentJob(e.node);
    }
  };
  // 执行实际操作 begin
  // 添加
  const addJob = async (job) => {
    let res = await request("/job/add", job, "post");
    if (res.code >= 0) {
      setAddShow(false);
      setAddingJob({ name: "", explain: "", departmentId: undefined });
      message.success(res.message);
      setJobTrees(
        jobTreesAdd(jobTrees, {
          ...res.data,
          icon: <CarryOutOutlined />,
          selectable: true,
        })
      );
      setCurrentJob({ ...res.data });
    } else {
      message.error(res.message);
    }
  };
  // 修改
  const updateJob = async (job) => {
    let res = await requestDispatch(
      dispatch,
      "/job/update",
      { ...job },
      "post"
    );
    if (res.code >= 0) {
      setIsUpdating(false);
      setUpdatingJob({});
      message.success(res.message);
      setJobTrees(jobTreesUpdate(jobTrees, res.data));
      setCurrentJob({ ...currentJob, ...res.data });
    } else {
      message.error(res.message);
    }
  };
  // 删除
  const deleteJob = async (id) => {
    let res = await requestDispatch(dispatch, "/job/delete", { id }, "post");
    if (res.code >= 0) {
      message.success(res.message);
      setJobTrees(jobTreesDelete(jobTrees, id));
      setCurrentJob(getFistJob(jobTrees));
    } else {
      message.error(res.message);
    }
  };
  // 执行实际操作 end

  // 修改本地数据 begin

  // 修改职位
  const jobTreesUpdate = (trees, job) => {
    return trees.reduce((acc, cur) => {
      if (cur.childrenDeps) {
        let children = jobTreesUpdate(cur.childrenDeps, job);
        acc.push({ ...cur, childrenDeps: children });
      } else {
        // 如果当前是job 且id相等 更新cur
        if (cur.id === job.id) {
          acc.push({ ...cur, ...job });
        } else {
          acc.push({ ...cur });
        }
      }
      return acc;
    }, []);
  };
  // 添加职位
  const jobTreesAdd = (trees, job) => {
    return trees.reduce((acc, cur) => {
      if (cur.childrenDeps) {
        let children = jobTreesAdd(cur.childrenDeps, job);
        if (cur.id === job.departmentId) {
          acc.push({ ...cur, childrenDeps: [job, ...children] });
        } else {
          acc.push({ ...cur, childrenDeps: children });
        }
      } else {
        acc.push({ ...cur });
      }
      return acc;
    }, []);
  };
  // 删除职位
  const jobTreesDelete = (trees, jobId) => {
    console.log(trees, "trees");
    return trees.reduce((acc, cur) => {
      if (cur.childrenDeps) {
        let children = jobTreesDelete(cur.childrenDeps, jobId);
        acc.push({ ...cur, childrenDeps: children });
      } else {
        if (cur.id === jobId) {
        } else {
          acc.push({ ...cur });
        }
      }
      return acc;
    }, []);
  };
  // 修改本地数据 end

  // 展示添加模态框
  const showAddModal = async (depId) => {
    console.log(depId, "depId");
    setAddingJob({ name: "", explain: "", departmentId: depId });
    setAddShow(true);
  };
  // 切换编辑
  const showUpdate = async () => {
    setUpdatingJob({
      id: currentJob.id,
      name: currentJob.name,
      explain: currentJob.explain,
    });
    setIsUpdating(true);
  };
  return (
    <Layout>
      <AddJob
        job={addingJob}
        open={addShow}
        onOk={addJob}
        onCancel={() => setAddShow(false)}
      ></AddJob>
      <div className="container">
        <div className="container-left">
          <Tree
            treeData={jobTrees}
            showIcon={true}
            expandAction="click"
            defaultExpandParent={true}
            expandedKeys={expandedKeys}
            onExpand={(keys) => setExpandedKeys(keys)}
            fieldNames={{
              title: "name",
              key: "id",
              children: "childrenDeps",
            }}
            blockNode
            onSelect={selectedChange}
          ></Tree>
        </div>
        <div className="container-right">
          <Descriptions
            layout="vertical"
            bordered
            items={items}
            title="部门信息"
            extra={
              isUpdating ? (
                <div className="extra">
                  <div
                    className="extra-btn"
                    onClick={() => setIsUpdating(false)}
                  >
                    <MyButton>{"取消"}</MyButton>
                  </div>
                  <div
                    className="extra-btn"
                    onClick={() =>
                      updateJob({
                        id: updatingJob.id,
                        name: updatingJob.name,
                        explain: updatingJob.explain,
                      })
                    }
                  >
                    <MyButton type={"primary"}>{"保存"}</MyButton>
                  </div>
                </div>
              ) : (
                <div className="extra">
                  <Popconfirm
                    title="删除职位"
                    description="您确定要删除该职位吗?"
                    onConfirm={() => deleteJob(currentJob.id)}
                    okText="确认"
                    cancelText="取消"
                  >
                    <div className="extra-btn">
                      <MyButton type="danger">删除</MyButton>
                    </div>
                  </Popconfirm>
                  <div className="extra-btn" onClick={showUpdate}>
                    <MyButton type={"warning"}>{"编辑"}</MyButton>
                  </div>
                </div>
              )
            }
          />
        </div>
      </div>
    </Layout>
  );
};
export default Job;
